package k8s

import (
	"github.com/infraboard/mcube/logger"
	"github.com/infraboard/mcube/logger/zap"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/rest"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/tools/clientcmd/api"
	"kubernetes-manage/k8s/list"
)

type K8sClient struct {
	restclient *rest.Config
	kubeconf   *api.Config
	client     *kubernetes.Clientset
	log        logger.Logger
}

func NewClient(kubeconfig string) (*K8sClient, error) {
	// 通过传递kubeconfig内容，加载kubeconfig配置
	kubeconf, err := clientcmd.Load([]byte(kubeconfig))
	if err != nil {
		return nil, err
	}

	// 构造restconf客户端
	restconf, err := clientcmd.BuildConfigFromKubeconfigGetter("", func() (*api.Config, error) {
		return kubeconf, nil
	})

	if err != nil {
		return nil, err
	}

	// 初始化k8s集群客户端
	client, err := kubernetes.NewForConfig(restconf)
	if err != nil {
		return nil, err
	}
	return &K8sClient{
		kubeconf:   kubeconf,
		restclient: restconf,
		client:     client,
		log:        zap.L().Named("k8s"),
	}, nil
}

// 获取集群版本
func (c *K8sClient) ServerVersion() string {
	clusterinfo, err := c.client.ServerVersion()
	if err != nil {
		c.log.Debugf("get cluster service error: %s", err)
	}
	c.log.Debugf("cluster info: %s", clusterinfo)
	return clusterinfo.String()
}

// 获取集群资源信息
func (c *K8sClient) List() *list.Client {
	return list.NewListClient(c.client)
}
